<?php

class yunsimpleApi extends IController{

    function cart2()
    {
        $id        = isset($_REQUEST['id']) ? IFilter::act($_REQUEST['id'], 'int') : 0;
        $type      = isset($_REQUEST['type']) ? IFilter::act($_REQUEST['type']) : '';//goods,product
        $promo     = isset($_REQUEST['promo']) ? IFilter::act($_REQUEST['promo']) : '';
        $active_id = isset($_REQUEST['active_id']) ? IFilter::act($_REQUEST['active_id'], 'int') : 0;
        $buy_num   = isset($_REQUEST['num']) ? IFilter::act($_REQUEST['num'], 'int') : 1;
        $result_array = array();
//        $tourist   = IReq::get('tourist');//游客方式购物

        //必须为登录用户
        if($this->user['user_id'] == null)
        {
            if($id == 0 || $type == '')
            {
                Yun::ajaxReturn(1, '失败');
            }
            else
            {
                Yun::ajaxReturn(1, '失败', array('id' => $id, 'type' => $type, 'num' => $buy_num, 'promo' => $promo ? $promo : '', 'active_id' => $active_id ? $active_id : ''));
            }
        }

        $user_id = $this->user['user_id'];

        //计算商品
        $countSumObj = new CountSum($user_id);
        $result = $countSumObj->cart_count($id,$type,$buy_num,$promo,$active_id);

        if($countSumObj->error)
        {
            //IError::show(403,$countSumObj->error);
            Yun::ajaxReturn(1, $countSumObj->error);
        }

        //获取收货地址
        $addressObj  = new IModel('address');
        $addressList = $addressObj->query('user_id = '.$user_id,"*","is_default desc");

        //收货地址选中状态判断
        $chk_addrid = ICookie::get('chk_addrid');
        $has_addrid = false;
        foreach ( $addressList as $key => $val ) {
            if ( $chk_addrid == $val['id'] ) {
                $has_addrid = true;
                break;
            }
        }
        if ( !$has_addrid ) {
            $chk_addrid = 0;
            ICookie::clear('chk_addrid');
        }

        //默认地址的自我修正
        Yun::fixAddressDefault($addressList);

        //更新$addressList数据
        foreach($addressList as $key => $val)
        {
            $temp = area::name($val['province'],$val['city'],$val['area']);
            if(isset($temp[$val['province']]) && isset($temp[$val['city']]) && isset($temp[$val['area']]))
            {
                $addressList[$key]['province_val'] = $temp[$val['province']];
                $addressList[$key]['city_val']     = $temp[$val['city']];
                $addressList[$key]['area_val']     = $temp[$val['area']];
            }

            //选中的地址
            if ( $chk_addrid > 0 ) {
                if ( $chk_addrid == $val['id'] ) {
                    $addressList[$key]['checked'] = 1;
                    ICookie::set('chk_addrid',$val['id']);
                } else {
                    $addressList[$key]['checked'] = 0;
                }
            } else {
                if ( $val['is_default'] == 1 ) {
                    $addressList[$key]['checked'] = 1;
                    ICookie::set('chk_addrid',$val['id']);
                } else {
                    $addressList[$key]['checked'] = 0;
                }
            }
        }

        //为了适应WAP需要，地址管理返回addr_id用于选中状态
        $chk_ticketid = isset($_REQUEST['chk_ticketid']) ? IFilter::act($_REQUEST['chk_ticketid'], 'int') : 0;
        //选中的优惠券
        if ( $chk_ticketid > 0 ) {
            $query = new IModel('prop');
            $where  = "id = {$chk_ticketid}";
            $ticket_items = $query->getObj($where);
            $result_array['ticket_items'] = $ticket_items;
            $ticket_value = $ticket_items['value'] >= $result['final_sum'] ? $result['final_sum'] : $ticket_items['value'];
            $result['final_sum'] = round($result['final_sum'] - $ticket_value,2);
        }
        //获取习惯方式
        $memberObj = new IModel('member');
        $memberRow = $memberObj->getObj('user_id = '.$user_id, 'custom');
        if(isset($memberRow['custom']) && $memberRow['custom'])
        {
            $result_array['custom'] = unserialize($memberRow['custom']);
        }
        else
        {
            $result_array['custom'] = array(
                'payment'  => '',
                'delivery' => '',
            );
        }

        //返回值
        $result_array['gid'] = $id;
        $result_array['type'] = $type;
        $result_array['num'] = $buy_num;
        $result_array['promo'] = $promo;
        $result_array['active_id'] = $active_id;
        $result_array['final_sum'] = $result['final_sum'];
        $result_array['promotion'] = $result['promotion'];
        $result_array['proReduce'] = $result['proReduce'];
        $result_array['sum'] = $result['sum'];
        $result_array['goodsList'] = $result['goodsList'][0];
        $result_array['count'] = $result['count'];
        $result_array['reduce'] = $result['reduce'];
        $result_array['weight'] = $result['weight'];
        $result_array['freeFreight'] = $result['freeFreight'];
        $result_array['seller'] = $result['seller'];
        //收货地址列表
        $result_array['addressList'] = $addressList;

        //获取商品税金
        $result_array['goodsTax'] = $result['tax'];

        Yun::ajaxReturn(0, '成功', $result_array);
    }

    /**
     * 生成订单
     */
    function cart3()
    {
        $address_id    = IFilter::act(IReq::get('radio_address'),'int');
        $delivery_id   = 1;
        $accept_time   = IFilter::act(IReq::get('accept_time'));
        $payment       = 1;
        $order_message = IFilter::act(IReq::get('message'));
        $ticket_id     = IFilter::act(IReq::get('ticket_id'),'int');
        $taxes         = IFilter::act(IReq::get('taxes'),'float');
        $tax_title     = IFilter::act(IReq::get('tax_title'));
        $gid           = IFilter::act(IReq::get('direct_gid'),'int');
        $num           = IFilter::act(IReq::get('direct_num'),'int');
        $type          = IFilter::act(IReq::get('direct_type'));//商品或者货品
        $promo         = IFilter::act(IReq::get('direct_promo'));
        $active_id     = IFilter::act(IReq::get('direct_active_id'),'int');
        $order_type    = 0;
        $dataArray     = array();
        $user_id       = ($this->user['user_id'] == null) ? 0 : $this->user['user_id'];

        //获取商品数据信息
        $countSumObj = new CountSum($user_id);
        $goodsResult = $countSumObj->cart_count($gid,$type,$num,$promo,$active_id);

        if($countSumObj->error)
        {
            Yun::ajaxReturn(1, $countSumObj->error);
        }

        //处理收件地址
        //1,访客; 2,注册用户
        if($user_id == 0)
        {
            Yun::ajaxReturn(1, '当前账户未注册');
        }
        else
        {
            $addressDB = new IModel('address');
            $addressRow= $addressDB->getObj('id = '.$address_id.' and user_id = '.$user_id);
        }

        if(!$addressRow)
        {
            Yun::ajaxReturn(1,"收货地址信息不存在");
        }
        $accept_name   = IFilter::act($addressRow['accept_name'],'name');
        $province      = $addressRow['province'];
        $city          = $addressRow['city'];
        $area          = $addressRow['area'];
        $address       = IFilter::act($addressRow['address']);
        $mobile        = IFilter::act($addressRow['mobile'],'mobile');
        $telphone      = IFilter::act($addressRow['telphone'],'phone');
        $zip           = IFilter::act($addressRow['zip'],'zip');

        //检查订单重复
        $checkData = array(
            "accept_name" => $accept_name,
            "address"     => $address,
            "mobile"      => $mobile,
            "distribution"=> $delivery_id,
        );
        $result = order_class::checkRepeat($checkData,$goodsResult['goodsList']);
        if( is_string($result) )
        {
            //IError::show(403,$result);
            Yun::ajaxReturn(1,$result);
        }

        if(!$gid)
        {
            //清空购物车
            IInterceptor::reg("cart@onFinishAction");
        }

        //判断商品是否存在
        if(is_string($goodsResult) || empty($goodsResult['goodsList']))
        {
            //IError::show(403,'商品数据错误');
            Yun::ajaxReturn(1,'商品数据错误');
        }

        //加入促销活动
        if($promo && $active_id)
        {
            $activeObject = new Active($promo,$active_id,$user_id,$gid,$type,$num);
            $order_type = $activeObject->getOrderType();
        }

        //最终订单金额计算
        $orderData = $countSumObj->countOrderFee($goodsResult,$province,$delivery_id,$payment,$taxes,0,$promo,$active_id);
        if(is_string($orderData))
        {
            //IError::show(403,$orderData);
            Yun::ajaxReturn(1,$orderData);
            exit;
        }

        //根据商品所属商家不同批量生成订单
        $orderIdArray  = array();
        $orderNumArray = array();
        $final_sum     = 0;
        foreach($orderData as $seller_id => $goodsResult)
        {
            //生成的订单数据
            $dataArray = array(
                'order_no'            => Order_Class::createOrderNum(),
                'user_id'             => $user_id,
                'accept_name'         => $accept_name,
                'pay_type'            => $payment,
                'distribution'        => $delivery_id,
                'postcode'            => $zip,
                'telphone'            => $telphone,
                'province'            => $province,
                'city'                => $city,
                'area'                => $area,
                'address'             => $address,
                'mobile'              => $mobile,
                'create_time'         => ITime::getDateTime(),
                'postscript'          => $order_message,
                'accept_time'         => $accept_time,
                'exp'                 => $goodsResult['exp'],
                'point'               => $goodsResult['point'],
                'type'                => $order_type,

                //商品价格
                'payable_amount'      => $goodsResult['sum'],
                'real_amount'         => $goodsResult['final_sum'],

                //运费价格
                'payable_freight'     => $goodsResult['deliveryOrigPrice'],
                'real_freight'        => $goodsResult['deliveryPrice'],

                //手续费
                'pay_fee'             => $goodsResult['paymentPrice'],

                //税金
                'invoice'             => $tax_title ? 1 : 0,
                'invoice_title'       => $tax_title,
                'taxes'               => $goodsResult['taxPrice'],

                //优惠价格
                'promotions'          => $goodsResult['proReduce'] + $goodsResult['reduce'],

                //订单应付总额
                'order_amount'        => $goodsResult['orderAmountPrice'],

                //订单保价
                'insured'             => $goodsResult['insuredPrice'],

                //自提点ID
                'takeself'            => 0,//业务无自提点

                //促销活动ID
                'active_id'           => $active_id,

                //商家ID
                'seller_id'           => $seller_id,

                //备注信息
                'note'                => '',
            );

            //获取红包减免金额
            if($ticket_id)
            {
                $memberObj = new IModel('member');
                $memberRow = $memberObj->getObj('user_id = '.$user_id,'prop,custom');
                foreach($ticket_id as $tk => $tid)
                {
                    //游客手动添加或注册用户道具中已有的代金券
                    if(ISafe::get('ticket_'.$tid) == $tid || stripos(','.trim($memberRow['prop'],',').',',','.$tid.',') !== false)
                    {
                        $propObj   = new IModel('prop');
                        $ticketRow = $propObj->getObj('id = '.$tid.' and NOW() between start_time and end_time and type = 0 and is_close = 0 and is_userd = 0 and is_send = 1');
                        if(!$ticketRow)
                        {
                            //IError::show(403,'代金券不可用');
                            Yun::ajaxReturn(1,'代金券不可用');
                        }

                        if($ticketRow['seller_id'] == 0 || $ticketRow['seller_id'] == $seller_id)
                        {
                            $ticketRow['value']         = $ticketRow['value'] >= $goodsResult['final_sum'] ? $goodsResult['final_sum'] : $ticketRow['value'];
                            $dataArray['prop']          = $tid;
                            $dataArray['promotions']   += $ticketRow['value'];
                            $dataArray['order_amount'] -= $ticketRow['value'];
                            $goodsResult['promotion'][] = array("plan" => "代金券","info" => "使用了￥".$ticketRow['value']."代金券");

                            //锁定红包状态
                            $propObj->setData(array('is_close' => 2));
                            $propObj->update('id = '.$tid);

                            unset($ticket_id[$tk]);
                            break;
                        }
                    }
                }
            }

            //促销规则
            if(isset($goodsResult['promotion']) && $goodsResult['promotion'])
            {
                foreach($goodsResult['promotion'] as $key => $val)
                {
                    $dataArray['note'] .= join("，",$val)."。";
                }
            }

            $dataArray['order_amount'] = $dataArray['order_amount'] <= 0 ? 0 : $dataArray['order_amount'];

            //生成订单插入order表中
            $orderObj  = new IModel('order');
            $orderObj->setData($dataArray);
            $order_id = $orderObj->add();

            if($order_id == false)
            {
                Yun::ajaxReturn(1,'订单生成错误');
            }

            /*将订单中的商品插入到order_goods表*/
            $orderInstance = new Order_Class();
            $orderInstance->insertOrderGoods($order_id,$goodsResult['goodsResult']);

            //订单金额小于等于0直接免单
            if($dataArray['order_amount'] <= 0)
            {
                Order_Class::updateOrderStatus($dataArray['order_no']);
            }
            else
            {
                $orderIdArray[]  = $order_id;
                $orderNumArray[] = $dataArray['order_no'];
                $final_sum      += $dataArray['order_amount'];
            }
        }

        //记录用户默认习惯的数据
        if(!isset($memberRow['custom']))
        {
            $memberObj = new IModel('member');
//            $memberRow = $memberObj->getObj('user_id = '.$user_id,'custom');
        }

        $memberData = array(
            'custom' => serialize(
                array(
                    'payment'  => $payment,
                    'delivery' => $delivery_id,
                )
            ),
        );
        $memberObj->setData($memberData);
        $memberObj->update('user_id = '.$user_id);

        //收货地址的处理
        if($user_id)
        {
            $addressDefRow = $addressDB->getObj('user_id = '.$user_id.' and is_default = 1');
            if(!$addressDefRow)
            {
                $addressDB->setData(array('is_default' => 1));
                $addressDB->update('user_id = '.$user_id.' and id = '.$address_id);
            }
        }

        $return_data = array();

        //获取备货时间
        $this->stockup_time = $this->_siteConfig->stockup_time ? $this->_siteConfig->stockup_time : 2;

        //数据渲染
        $return_data['order_id'] = join("_",$orderIdArray);
        $return_data['final_sum'] = round($final_sum,2);
        $return_data['count_money'] = round($dataArray['real_amount'] + $dataArray['real_freight'],2);
        $return_data['order_num'] = join(",",$orderNumArray);
        $return_data['create_time'] = $dataArray['create_time'];
        $return_data['delivery'] = '包邮';//数据库是“快递”
        $return_data['tax_title'] = $tax_title;
        $return_data['deliveryType'] = 0;
        $return_data['data'] = $dataArray;
        Yun::ajaxReturn(0, '成功', $return_data);

//        //订单金额为0时，订单自动完成
//        if($return_data['final_sum'] <= 0)
//        {
//            Yun::ajaxReturn(0, '成功', $return_data);
//        }
//        else
//        {
//            //支付环境系统自动判断
//            if ( Yun::is_weixin() ) {
//                $payment_url = IUrl::creatUrl('/yunblock/doPay/order_id/'.$this->order_id.'/payment_id/13');//见支付配置表
//
//                $js = 'window.location.href=\''.$payment_url.'\'';
//                Yun::ajaxReturn(0,'','',$js);
//            } else {
//                $this->payment_id = 16;//见payment配置
//                $this->payment_id = 8;//见payment配置
//            }
//
//            Yun::ajaxReturn(0, '成功', $dataArray);
//        }
    }

    /**
     * 获取代金券
     */
    public function get_redpacket(){
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $pageSize = isset($_REQUEST['pagesize']) ? $_REQUEST['pagesize'] : 20;
        $user_id = ($this->user['user_id'] == null) ? 0 : $this->user['user_id'];
        $member_info = Api::run('getMemberInfo', $user_id);
        $propIds     = trim($member_info['prop'], ',');
        $propIds     = $propIds ? $propIds : 0;
        $query = new IQuery('prop');
        $query->where  = "id in(".$propIds.") and is_send = 1 and NOW() between start_time and end_time";
        $count = count($query->find());
        $query->page   = $page;
        $query->pagesize = $pageSize;
        $items = $query->find();
        if($items){
            $array = array('page' => array('page_total' => ceil($count/$pageSize), 'page' => $page, 'page_size' => $pageSize), 'listData' => $items);
            Yun::ajaxReturn(0, '成功', $array);
        }else{
            Yun::ajaxReturn(1, '未查询到相关数据');
        }
    }
}